import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'dart:math' as math;

import 'animation_logic.dart';

class AnimationPage extends StatelessWidget {
  const AnimationPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final AnimationLogic logic = Get.put(AnimationLogic());

    return Scaffold(
      appBar: AppBar(
        title: const Text('说话嘴型动画'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 嘴型动画
            Obx(() => MouthAnimation(
                  volume: logic.volume.value,
                  isPlaying: logic.isPlaying.value,
                )),
            const SizedBox(height: 40),
            // 控制按钮
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ElevatedButton(
                  onPressed: () => logic.togglePlayback(),
                  child: Obx(() => Text(
                      logic.isPlaying.value ? '停止播放' : '开始播放')),
                ),
                const SizedBox(width: 20),
                ElevatedButton(
                  onPressed: () => logic.recordVoice(),
                  child: const Text('录制声音'),
                ),
              ],
            ),
            const SizedBox(height: 20),
            // 音量调节
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 40),
              child: Row(
                children: [
                  const Text('音量:'),
                  Expanded(
                    child: Slider(
                      value: logic.volume.value,
                      min: 0,
                      max: 1,
                      onChanged: (value) => logic.setVolume(value),
                    ),
                  ),
                  Obx(() => Text('${(logic.volume.value * 100).toInt()}%')),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class MouthAnimation extends StatefulWidget {
  final double volume;
  final bool isPlaying;

  const MouthAnimation({
    Key? key,
    required this.volume,
    required this.isPlaying,
  }) : super(key: key);

  @override
  State<MouthAnimation> createState() => _MouthAnimationState();
}

class _MouthAnimationState extends State<MouthAnimation>
    with SingleTickerProviderStateMixin {
  late AnimationController _controller;
  late Animation<double> _animation;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 300),
    );

    _animation = Tween<double>(begin: 0.0, end: 1.0).animate(_controller);
  }

  @override
  void didUpdateWidget(MouthAnimation oldWidget) {
    super.didUpdateWidget(oldWidget);
    
    // 根据音量和播放状态更新动画
    if (widget.isPlaying) {
      if (widget.volume > 0.1) {
        // 根据音量设置动画目标值
        _controller.animateTo(widget.volume);
      } else {
        // 音量太小时关闭嘴巴
        _controller.animateTo(0.0);
      }
    } else {
      // 不播放时关闭嘴巴
      _controller.animateTo(0.0);
    }
  }

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedBuilder(
      animation: _animation,
      builder: (context, child) {
        return Container(
          width: 200,
          height: 200,
          decoration: BoxDecoration(
            color: Colors.amber.shade100,
            shape: BoxShape.circle,
          ),
          child: CustomPaint(
            painter: MouthPainter(
              openRatio: _animation.value,
            ),
          ),
        );
      },
    );
  }
}

class MouthPainter extends CustomPainter {
  final double openRatio;

  MouthPainter({required this.openRatio});

  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);
    
    // 绘制眼睛
    final eyePaint = Paint()
      ..color = Colors.black
      ..style = PaintingStyle.fill;
    
    // 左眼
    canvas.drawCircle(
      Offset(center.dx - 40, center.dy - 30),
      8,
      eyePaint,
    );
    
    // 右眼
    canvas.drawCircle(
      Offset(center.dx + 40, center.dy - 30),
      8,
      eyePaint,
    );
    
    // 绘制嘴巴
    final mouthPaint = Paint()
      ..color = Colors.red
      ..style = PaintingStyle.fill;
    
    // 嘴巴的开合程度由openRatio控制
    final mouthHeight = 10 + 40 * openRatio;
    
    // 嘴巴形状
    final mouthRect = Rect.fromCenter(
      center: Offset(center.dx, center.dy + 30),
      width: 80,
      height: mouthHeight,
    );
    
    // 绘制嘴巴
    canvas.drawOval(mouthRect, mouthPaint);
    
    // 绘制嘴唇轮廓
    final lipPaint = Paint()
      ..color = Colors.black
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2;
    
    canvas.drawOval(mouthRect, lipPaint);
  }

  @override
  bool shouldRepaint(MouthPainter oldDelegate) {
    return oldDelegate.openRatio != openRatio;
  }
}
